package com.example.controller;


import com.alibaba.fastjson2.JSONObject;
import com.example.enetity.Result;
import com.example.enetity.User;
import com.example.service.UserService;
import com.example.utils.JwtUtil;
import com.example.utils.Md5Util;
import com.example.utils.getRedisDataUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Slf4j
@RestController
@RequestMapping("/user")
//要加上注解注释
//支持跨域
@CrossOrigin
public class UserController {


    @Autowired
    private UserService service;

    @Autowired
    private StringRedisTemplate template;



    @PostMapping("/register")
    public Result register(@RequestBody @Validated User user) {
        //格式规范
        String username = user.getUsername();
        String password = user.getPassword();
        User u = service.findByUsername(username);
        if (u == null) {
            LocalDateTime now = LocalDateTime.now();
            service.register(username, password, now, now);
            return Result.success();
        } else {
            return Result.error("用户名被占用，请换一个吧");
        }
    }

    @PostMapping("/login")
    public Result<String> login(@RequestBody @Validated User user) {
        String username = user.getUsername();
        String password = user.getPassword();
        User u = service.findByUsername(username);
        if (u == null) {
            return Result.error("主人，您好像还没有注册呢");
        }
        if (Md5Util.getMD5String(password).equals(u.getPassword())) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("username",username);
            claims.put("id",u.getId());
            String token = JwtUtil.genToken(claims);
            ValueOperations<String, String> operations = template.opsForValue();
            operations.set(token,token,12, TimeUnit.HOURS);
            return Result.success("登陆成功", token);
        } else {
            return Result.error("密码好像有错的说");
        }
    }

    @GetMapping("/userInfo")
    public Result<User> userInfo() {
//        Map<String, Object> map = JwtUtil.parseToken(token);
//        String username = (String) map.get("username");
        String s = template.opsForValue().get("data");
        JSONObject jsonObject = JSONObject.parseObject(s);
        Map<String,Object> map = (Map<String,Object>)jsonObject;
        String username = (String) map.get("username");
        User user = service.findByUsername(username);
        return Result.success("获取用户信息成功",user);
    }

    //可由前端来编写
//    @PutMapping("/quit") //有问题稍后在弄
//    public Result<User> quit(){
//        ThreadLocalUtil.remove();
//        return Result.success("用户退出成功");
//    }

    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user){
        service.MyUpdate(user);
        return Result.success("修改成功");
    }

    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam String avatarUrl){
        service.updateAvatar(avatarUrl);
        return  Result.success("更新成功");
    }

    @PatchMapping("/updatePassword")
    public Result updatePassword(@RequestBody Map<String,String> PwdData,@RequestHeader(name = "Authorization") String token){
        String oldPwd = PwdData.get("oldPwd");
        String newPwd = PwdData.get("newPwd");
        String rePwd = PwdData.get("rePwd");
//        逻辑判断
        if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd)|| !StringUtils.hasLength(rePwd) ){
            return Result.error("输入好像有误呢，主人");
        }
        String s = template.opsForValue().get("data");
        JSONObject jsonObject = JSONObject.parseObject(s);
        Map<String,Object> map = (Map<String,Object>)jsonObject;
        String username = (String) map.get("username");
        User user = service.findByUsername(username);
        if (!user.getPassword().equals(Md5Util.getMD5String(oldPwd))){
            return Result.error("主人，原密码好像不对呀");
        }
        if (oldPwd.equals(newPwd)){
            return Result.error("密码不能和之前一样哦，主人");
        }
        if (!newPwd.equals(rePwd)){
            return Result.error("两次密码好像不一样呀，主人");
        }
        service.updatePassword(newPwd);
        ValueOperations<String, String> operations = template.opsForValue();
        operations.getOperations().delete(token);
        return Result.success("恭喜主人，密码修改成功");
    }
}
